// 工具函数模块

/**
 * 计算营养摄入和目标
 * @param {Object} eatData - 饮食数据对象
 * @returns {Object} 更新后的饮食数据
 */
async function calculateNutrition(eatData) {
  const Food = require("../../models/Food");
  const User = require("../../models/User");
  
  // 合并所有餐次的食物
  const allMeals = [
    ...(eatData.breakfast || []),
    ...(eatData.lunch || []),
    ...(eatData.dinner || []),
    ...(eatData.snacks || [])
  ];
  
  // 初始化今日营养摄入
  let calorie_today = 0;
  let fat_today = 0;
  let carbohydrate_today = 0;
  let protein_today = 0;
  
  // 计算每个食物的营养
  for (const meal of allMeals) {
    if (!meal.food_id || !meal.eat_num) continue;
    
    try {
      const food = await Food.findById(meal.food_id);
      if (!food || !food.components) continue;
      
      // 找到对应的单位
      const component = food.components.find(c => c.unit_name === meal.unit_name);
      if (!component) continue;
      
      // 累加营养值（单位营养值 * 食用数量）
      calorie_today += (component.calorie || 0) * meal.eat_num;
      fat_today += (component.fat || 0) * meal.eat_num;
      carbohydrate_today += (component.carbohydrate || 0) * meal.eat_num;
      protein_today += (component.protein || 0) * meal.eat_num;
    } catch (err) {
      console.error(`计算食物 ${meal.food_id} 营养失败:`, err);
    }
  }
  
  // 计算营养目标（基于用户信息）
  const user = await User.findOne({ openid: eatData.openid });
  let calorie_target = 2000; // 默认值
  let fat_target = 60;
  let carbohydrate_target = 250;
  let protein_target = 100;
  
  if (user && user.weight && user.height && user.age) {
    const exercise = eatData.exercise || 1.37;
    
    // 使用 Mifflin-St Jeor 公式计算基础代谢率 (BMR)
    let bmr;
    if (user.gender === 0) { // 男性
      bmr = 10 * user.weight + 6.25 * user.height - 5 * user.age + 5;
    } else { // 女性
      bmr = 10 * user.weight + 6.25 * user.height - 5 * user.age - 161;
    }
    
    // 总热量 = BMR × 运动系数
    calorie_target = Math.round(bmr * exercise);
    
    // 根据目标调整热量
    if (user.target === 1) { // 减重
      calorie_target = Math.round(calorie_target * 0.85); // 减少15%
    } else if (user.target === 2) { // 增重
      calorie_target = Math.round(calorie_target * 1.15); // 增加15%
    }
    
    // 计算三大营养素目标（按热量比例）
    // 脂肪：25-30%热量，1g脂肪=9卡
    fat_target = Math.round((calorie_target * 0.28) / 9);
    
    // 碳水化合物：45-55%热量，1g碳水=4卡
    carbohydrate_target = Math.round((calorie_target * 0.5) / 4);
    
    // 蛋白质：15-25%热量，1g蛋白质=4卡
    protein_target = Math.round((calorie_target * 0.22) / 4);
  }
  
  // 更新营养数据（四舍五入）
  eatData.score = {
    calorie_target,
    fat_target,
    carbohydrate_target,
    protein_target,
    calorie_today: Math.round(calorie_today),
    fat_today: Math.round(fat_today * 10) / 10,
    carbohydrate_today: Math.round(carbohydrate_today * 10) / 10,
    protein_today: Math.round(protein_today * 10) / 10
  };
  
  // 计算饮食评分（简单算法：目标达成度）
  const calorieScore = Math.min(100, (calorie_today / calorie_target) * 100);
  const fatScore = Math.min(100, 100 - Math.abs((fat_today / fat_target) - 1) * 100);
  const carbScore = Math.min(100, 100 - Math.abs((carbohydrate_today / carbohydrate_target) - 1) * 100);
  const proteinScore = Math.min(100, 100 - Math.abs((protein_today / protein_target) - 1) * 100);
  
  eatData.eat_score = Math.round((calorieScore + fatScore + carbScore + proteinScore) / 4);
  
  return eatData;
}

/**
 * 计算运动消耗
 * @param {Object} doData - 运动数据对象
 * @returns {Object} 更新后的运动数据
 */
async function calculateSportBurn(doData) {
  const Sport = require("../../models/Sport");
  
  // 获取今日运动记录
  const todaySports = doData.sport || [];
  
  // 初始化今日运动消耗
  let calorie_burn = 0;
  let fat_burn = 0;
  let carbohydrate_burn = 0;
  let protein_burn = 0;
  
  // 计算每个运动的消耗
  for (const sportRecord of todaySports) {
    if (!sportRecord.food_id || !sportRecord.eat_num) continue;
    
    try {
      const sport = await Sport.findById(sportRecord.food_id);
      if (!sport || !sport.components) continue;
      
      // 找到对应的单位
      const component = sport.components.find(c => c.unit_name === sportRecord.unit_name);
      if (!component) continue;
      
      // 累加消耗值（单位消耗值 * 运动数量）
      // 注意：运动的calorie是消耗，所以是正值
      calorie_burn += (component.calorie || 0) * sportRecord.eat_num;
      fat_burn += (component.fat || 0) * sportRecord.eat_num;
      carbohydrate_burn += (component.carbohydrate || 0) * sportRecord.eat_num;
      protein_burn += (component.protein || 0) * sportRecord.eat_num;
    } catch (err) {
      console.error(`计算运动 ${sportRecord.food_id} 消耗失败:`, err);
    }
  }
  
  // 更新运动消耗数据（四舍五入）
  if (!doData.score) {
    doData.score = {};
  }
  
  doData.score.calorie_burn = Math.round(calorie_burn);
  doData.score.fat_burn = Math.round(fat_burn * 10) / 10;
  doData.score.carbohydrate_burn = Math.round(carbohydrate_burn * 10) / 10;
  doData.score.protein_burn = Math.round(protein_burn * 10) / 10;
  
  return doData;
}

/**
 * 格式化时间戳为日期字符串
 * @param {number} time - Unix时间戳
 * @returns {string} 格式化后的日期 (MM/DD)
 */
function getdate(time) {
  const now = new Date(time * 1000);
  const m = now.getMonth() + 1;
  const d = now.getDate();
  return (m < 10 ? "0" + m : m) + "/" + (d < 10 ? "0" + d : d);
}

module.exports = {
  calculateNutrition,
  calculateSportBurn,
  getdate
};

